import sys
import os
import subprocess
from pathlib import Path

def setup_python_path():
    """设置Python路径"""
    # 获取项目根目录的绝对路径
    project_root = os.path.dirname(os.path.abspath(__file__))
    
    # 将项目根目录添加到 Python 路径
    if project_root not in sys.path:
        sys.path.insert(0, project_root)

def check_and_install_dependencies():
    """检查并安装依赖"""
    try:
        # 检查 requirements.txt 是否存在
        req_file = Path(__file__).parent / 'requirements.txt'
        if not req_file.exists():
            print("错误: 未找到 requirements.txt 文件")
            return False

        # 尝试导入必要的模块
        try:
            import PyQt5
            import cv2
            import numpy
            import selenium
            import requests
            import webdriver_manager
        except ImportError:
            # 如果导入失败，提示用户安装依赖
            print("\n检测到缺少必要的依赖，正在安装...")
            subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", str(req_file)])
            print("\n依赖安装完成。")

        return True

    except Exception as e:
        print(f"\n安装依赖时出错: {str(e)}")
        print("请手动运行: pip install -r requirements.txt")
        return False

def main():
    """主函数"""
    try:
        # 设置Python路径
        setup_python_path()

        # 检查并安装依赖
        if not check_and_install_dependencies():
            return 1

        # 导入必要的模块
        from src.utils.logger import logger
        from src.utils.init import initialize_app, check_deps, check_system
        
        # 检查系统要求
        system_issues = check_system()
        if system_issues:
            print("\n系统要求检查失败:")
            for issue in system_issues:
                print(f"  - {issue}")
            return 1
            
        # 检查依赖项
        missing_deps = check_deps()
        if missing_deps:
            print("\n缺少以下依赖项:")
            for dep in missing_deps:
                print(f"  - {dep}")
            print("\n请运行: pip install -r requirements.txt")
            return 1

        print("\n初始化应用程序...")
        if not initialize_app():
            print("错误: 应用程序初始化失败")
            return 1

        print("\n启动应用程序...")
        from src.gui.main_window import MainWindow
        from PyQt5.QtWidgets import QApplication
        
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        
        logger.info("应用程序界面已加载")
        return app.exec_()
        
    except ImportError as e:
        print(f"\n导入错误: {e}")
        print("请确保已安装所有必要的依赖")
        print(f"当前工作目录: {os.getcwd()}")
        return 1
    except Exception as e:
        print(f"\n运行错误: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
